package cn.rkylin.oms.warehouse.shiporder.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.ShiporderStatus;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.warehouse.shiporder.dao.ShiporderDAOImpl;
import cn.rkylin.oms.warehouse.shiporder.dao.ShiporderSkuDAOImpl;
import cn.rkylin.oms.warehouse.shiporder.service.ShiporderServiceImpl;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderSkuVO;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;

/**
 * 发货Controller
 * 
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Controller
@RequestMapping("/shiporder")
public class ShiporderController extends ApolloController {

    private static final Log logger = LogFactory.getLog(ShiporderController.class);
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShiporder";
    private static final String PAGE_SELECT_STATEMENT_ORDER = "pageSelectShiporderForOrder";
    private static final String PAGE_SUK_SELECT_STATEMENT = "selectShiporderSkuList";

    @Autowired
    private ShiporderServiceImpl shiporderServiceImpl;

    @Autowired
    private LogUtil logUtil;

    /**
     * 查询发货单列表
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            发货VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getShiporderList")
    public Map<String, Object> getShiporderList(String quickSearch, String formJson, String shiporderStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ShiporderVO param = new ShiporderVO();
            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            param = JSONObject.parseObject(formJson, ShiporderVO.class);
            // 快速查询检索条件
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                param.setQuickSearch(quickSearch);
            }
            param.setShiporderStatus(shiporderStatus);
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShiporderDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            PageInfo<ShiporderVO> stockInList = shiporderServiceImpl.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * jinshen 通过orderId检索发货信息
     * 
     * @param orderId
     * @param start
     * @param length
     * @return
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getShiporderListByOrderId")
    public Map<String, Object> getShiporderListByOrderId(String orderId, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ShiporderVO param = new ShiporderVO();
            param.setSourceId(orderId);
            param.setSourceType("or");

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShiporderDAOImpl.class.getName(), PAGE_SELECT_STATEMENT_ORDER, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            PageInfo<ShiporderVO> stockInList = shiporderServiceImpl.findByWhereForOrder(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * jinshen 通过orderId检索发货信息
     *
     * @param orderId
     * @param start
     * @param length
     * @return
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getShiporderListByOrderIdNoStorType")
    public Map<String, Object> getShiporderListByOrderIdNoStorType(String orderId, @RequestParam(required = false, defaultValue = "0") int start,
                                                         @RequestParam(required = false, defaultValue = "10") int length) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ShiporderVO param = new ShiporderVO();
            param.setSourceId(orderId);
            param.setSourceType("or");

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShiporderDAOImpl.class.getName(), "pageSelectShiporderForOrderNoStorType", replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            PageInfo<ShiporderVO> stockInList = shiporderServiceImpl.findByWhereForOrderNoStorType(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询发货单列表数量
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            发货VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getShiporderListCount")
    public Map<String, Object> getShiporderListount(String quickSearch, String formJson, String shiporderStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            Map waitSendOutGoodsMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.WAIT_SEND_OUT_GOODS, start, length);
            Map sendingOutGoodsMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.SENDING_OUT_GOODS, start, length);
            Map shipedMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.SHIPED, start, length);
            Map consignedMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.CONSIGNED, start, length);
            Map canceledMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.CANCELED, start, length);

            map.put(JSON_RESULT, SUCCESS);
            map.put("waitSendOutGoodsCount", waitSendOutGoodsMap.get(RECORDS_TOTAL));
            map.put("sendingOutGoodsCount", sendingOutGoodsMap.get(RECORDS_TOTAL));
            map.put("shipedCount", shipedMap.get(RECORDS_TOTAL));
            map.put("consignedCount", consignedMap.get(RECORDS_TOTAL));
            map.put("canceledCount", canceledMap.get(RECORDS_TOTAL));

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询发货单信息
     * 
     * @param shiporderId
     *            发货单Id
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = { "/getShiporderInfo/{shiporderId}" })
    public Map<String, Object> getShiporderInfo(@PathVariable String shiporderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShiporderVO shiporderVO = new ShiporderVO();
            shiporderVO.setShiporderId(shiporderId);
            ShiporderVO data = shiporderServiceImpl.getShiporderInfo(shiporderVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, data);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 查询发货单商品列表
     * 
     * @param shiporderId
     *            发货单Id
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = "/getShiporderSkuList")
    public Map<String, Object> getShiporderSkuList(String shiporderId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
            shiporderSkuVO.setShiporderId(shiporderId);
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            // 排序语句生成
            String orderStatement = getOrderString(ShiporderSkuDAOImpl.class.getName(), PAGE_SUK_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                shiporderSkuVO.setOrderBy(orderStatement);
            }

            List<ShiporderSkuVO> shiporderSkuVOList = shiporderServiceImpl.selectShiporderSkuList(shiporderSkuVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shiporderSkuVOList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 取消发货单
     * 
     * @param shiporderId
     *            发货单Id
     * @param shiporderStatus
     *            发货状态
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = { "/cancelShiporder" })
    @SystemControllerLog(module = "发货单管理", operation = "取消发货单", keyCode = "shiporderId")
    public Map<String, Object> cancelShiporder(@RequestBody ShiporderVO shiporderVO) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            String returnMsg = shiporderServiceImpl.cancelShiporder(shiporderVO.getShiporderId());

            logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "取消发货单", "发货单管理", "取消成功"));

            if ("取消成功".equals(returnMsg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, returnMsg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, returnMsg);
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog(shiporderVO.getShiporderCode(), "取消发货单", "发货单管理", ex.getMessage()));
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shiporderId", shiporderVO.getShiporderId());
        return returnMap;
    }

    /**
     * 批量取消发货单
     * 
     * @param shiporderVOList
     *            发货单VO列表
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = "/batchCancel", method = RequestMethod.POST)
    @SystemControllerLog(module = "发货单管理", operation = "批量取消发货单")
    public Map<String, Object> batchCancel(@RequestBody List<ShiporderVO> shiporderVOList) throws Exception {
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        String shiporderId = "";

        try {
            int successCount = 0;
            int failCount = 0;
            for (int i = 0; i < shiporderVOList.size(); i++) {
                shiporderId = shiporderVOList.get(i).getShiporderId();
                String returnMsg = shiporderServiceImpl.cancelShiporder(shiporderId);
                if ("取消成功".equals(returnMsg)) {
                    successCount++;
                } else {
                    failCount++;
                }

                logUtil.info(new DBLog(shiporderId, "批量取消发货单", "发货单管理", "批量取消成功"));
            }

            // 返回结果
            if (failCount == 0) {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RETURN_DATA, "批量取消成功" + successCount + "条");
            } else {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "批量取消成功" + successCount + "条，失败" + failCount + "条");
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog(shiporderId, "批量取消发货单", "发货单管理", ex.getMessage()));
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }

        return returnJSON;
    }

    /**
     * 构建发货单列表为合并订单
     * 
     * @return 构建得发货单列表
     * @throws Exception
     *             异常
     */
    private List<ShiporderVO> buildShiporderVOList(ShiporderVO shiporderVO) throws Exception {
        String tradeCode = shiporderVO.getTradeCode();
        String[] tradeCodeArray = tradeCode.split(",");
        List<ShiporderVO> shiporderVOList = new ArrayList<ShiporderVO>();
        for (int i = 0; i < tradeCodeArray.length; i++) {
            ShiporderVO shiporderData = new ShiporderVO();
            BeanUtils.copyProperties(shiporderVO,shiporderData);
            shiporderData.setTradeCode(tradeCodeArray[i]);
            shiporderVOList.add(shiporderData);
        }

        return shiporderVOList;
    }

    /**
     * 平台发货̬
     * 
     * @param shiporderId
     *            发货单Id
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = { "/consign" })
    @SystemControllerLog(module = "发货单管理", operation = "平台发货")
    public Map<String, Object> consign(@RequestBody ShiporderVO shiporderVO) throws Exception {
        List<ShiporderVO> shiporderVOList = new ArrayList<ShiporderVO>();
        shiporderVOList.add(shiporderVO);

        return this.batchConsign(shiporderVOList);
    }

    /**
     * 批量平台发货
     * 
     * @param shiporderVOList
     *            发货单VO列表
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = "/batchConsign", method = RequestMethod.POST)
    @SystemControllerLog(module = "发货单管理", operation = "批量平台发货")
    public Map<String, Object> batchConsign(@RequestBody List<ShiporderVO> shiporderVOList) throws Exception {
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        String shiporderCode = "";

        try {
            int successCount = 0;
            String returnData = "";

            // 拆分合并订单，构建发货单列表
            List<ShiporderVO> shiporderAllDataList = new ArrayList<ShiporderVO>();
            for (int i = 0; i < shiporderVOList.size(); i++) {
                List<ShiporderVO> shiporderDataList = buildShiporderVOList(shiporderVOList.get(i));
                shiporderAllDataList.addAll(shiporderDataList);
            }

            for (int i = 0; i < shiporderAllDataList.size(); i++) {
                ShiporderVO shiporderData = shiporderAllDataList.get(i);
                shiporderCode = shiporderData.getShiporderCode();
                Map<String, String> resultMap = shiporderServiceImpl.consign(shiporderData);

                if (YesNoConst.YES.equals(resultMap.get("success"))) {
                    successCount++;
                } else {
                    returnData = returnData + ", 发货单编号:" + shiporderData.getShiporderCode() + resultMap.get("msg");
                }

                logUtil.info(new DBLog(shiporderCode, "平台发货", "发货单管理", "发货成功"));
            }
            if (successCount != 0) {
                returnData = "平台发货成功" + successCount + "条" + returnData;
            } else {
                returnData = returnData.substring(1);
            }

            // 返回结果
            if (successCount == shiporderAllDataList.size()) {
                returnJSON.put(JSON_RESULT, SUCCESS);
                returnJSON.put(RETURN_DATA, returnData);
            } else {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, returnData);
            }
        } catch (Exception ex) {
            logUtil.info(new DBLog(shiporderCode, "平台发货", "发货单管理", ex.getMessage()));
            logger.error(ex.getMessage(), ex);
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }

        return returnJSON;
    }

    /**
     * 锁定发货单为退款单 http://localhost:8081/shiporder/lockForSysRefund.action
     * 
     * @param orderId
     *            订单Id
     * @return 结果Map
     */
    @RequestMapping(value = "/lockForSysRefund", method = RequestMethod.GET)
    @ResponseBody
    @SystemControllerLog(module = "发货单管理", operation = "锁定发货单为退款单", keyCode = "orderId")
    public Map<String, Object> lockForSysRefund(String orderId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            String returnMsg = shiporderServiceImpl.lockForSysRefund(orderId);

            logUtil.info(new DBLog(orderId, "根据退款单锁定发货单", "发货单管理", "锁定成功"));

            if ("".equals(returnMsg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, returnMsg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, returnMsg);
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog(orderId, "根据退款单锁定发货单", "发货单管理", ex.getMessage()));
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("orderId", orderId);
        return returnMap;
    }

}
